const fs = require('fs');
const userService = require('../service/user.service')
const errorTypes = require('../constans/error-types')
const { AVATAR_PATH } = require('../constans/file-path')

class UserController {
    async create(ctx, next) {
        // 获取用户请求传递的参数
        const user = ctx.request.body
        // 查询数据
        const result = await userService.create(user)
        // 返回数据
        ctx.body = result
    }
    async getUsers(ctx, next) {
        const { id } = ctx.request.params
        const result = await userService.getUserByID(id)
        if (!result.length) {
            const error = new Error(errorTypes.USER_DOES_NOT_EXISTS);
            return ctx.app.emit('error', error, ctx);
        }
        ctx.body = result[0]
    }
    async getAvatar(ctx, next) {
        const { id } = ctx.params
        const avatarInfo = await userService.getUserAvatar(id)
        ctx.response.set('content-type', avatarInfo.mimetype);
        ctx.body = fs.createReadStream(`${AVATAR_PATH}/${avatarInfo.filename}`);
    }
}

module.exports = new UserController()